﻿namespace Bowlus.Common
{
    using System.Collections.Generic;
    using System.Linq;

    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.StorageClient;

    public class TentantDepTableContext : TableServiceContext
    {

        private const string TenantDeploymentTable = "TenantDeployment";

        private static readonly object LockObject = new object();

        private static volatile TentantDepTableContext instance;

        // create table if it does not exist.
        private TentantDepTableContext(CloudStorageAccount account)
            : base(account.TableEndpoint.AbsoluteUri, account.Credentials)
        {
            var ctc = new CloudTableClient(account.TableEndpoint.AbsoluteUri, account.Credentials);
            if (ctc.CreateTableIfNotExist(TenantDeploymentTable))
            {
                var td = new TenantDeployment { RowKey = "initalizer" };
                this.AddTD(td);
                DeleteObject(td);
                SaveChanges();
            }
        }

        public static TentantDepTableContext Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (LockObject)
                    {
                        if (instance == null)
                        {
                            return instance = new TentantDepTableContext(BowlusSettings.StorageAccount);
                        }
                    }
                }
                return instance;
            }
        }

        // tenant deployment info in a list
        public IQueryable<TenantDeployment> TDQueryable
        {
            get
            {
                return CreateQuery<TenantDeployment>(TenantDeploymentTable).Where(c => c.PartitionKey == "_bowlus");
            }
        }

        // update list of tenants
        public void UpdateTDs(IEnumerable<TenantDeployment> td)
        {
            foreach (var deployment in td)
            {
                UpdateObject(deployment);
            }
            SaveChanges();
        }

        // add a tenant
        public void AddTD(TenantDeployment td)
        {
            AddObject(TenantDeploymentTable, td);
            SaveChanges();
        }

        public void UpdateTD(TenantDeployment td)
        {
            UpdateObject(td);
            SaveChanges();
        }

        public void DeleteTD(TenantDeployment td)
        {
            DeleteObject(td);
            SaveChanges();
        }

    }
}
